/**
 * ajax请求 工具类
 * 
 * @param url
 *            地址
 * @param data
 *            传输的数据 json
 * @param successCB
 *            请求成功后的回调函数
 */
var HttpUtil = {
    post: function (url, data, successCB, async) {
        this.common(url, data, successCB, 'post', async);
    },
    postHeader: function (url, data, successCB, async,authorization) {
        this.commonHeader(url, data, successCB, 'post', async,authorization);
    },
    get: function (url, data, successCB, async) {
        this.common(url, data, successCB, 'get', async);
    },
    common: function (url, data, successCB, method, async) {
        $.ajax({
            url: url,
            data: data,
            type: method,
            dataType : "json",
            contentType:'application/x-www-form-urlencoded',
            async: async == false ? false : true,
            success: function (json) {
                successCB(json)
            },
            error: function (json) {
                console.log('请求失败，msg:', json)
                //weui.topTips('系统繁忙，请重试');
                layer.alert("请求失败，msg:"+json);
            }
        });
    },
    commonHeader: function (url, data, successCB, method, async, authorization) {
        $.ajax({
            url: url,
            data: data,
            type: method,
            dataType : "json",
            async: async == false ? false : true,
            success: function (json) {
                successCB(json)
            },
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", authorization);
            },
            error: function (json) {
                console.log('请求失败，msg:', json)
                //weui.topTips('系统繁忙，请重试');
                layer.alert("请求失败，msg:"+json);
            }
        });
    },
    convertDateFromString:function(dateString) {
    	if (dateString) {
    		var date = new Date(dateString.replace(/-/,"/"));
    		return date;
    	}
    },
    fmtDate:function(obj){
    	if(obj==null) return "";
        var date =  new Date(obj);
        var y = 1900+date.getYear();
        var m = "0"+(date.getMonth()+1);
        var d = "0"+date.getDate();
        return y+"-"+m.substring(m.length-2,m.length)+"-"+d.substring(d.length-2,d.length);
    },
    // formatDuringn(mss) {// 转换时分秒
    //     var hours = parseInt((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    //     var minutes = parseInt((mss % (1000 * 60 * 60)) / (1000 * 60));
    //     var seconds = (mss % (1000 * 60)) / 1000;
    //
    //     hours = hours < 10 ? ('0' + hours) : hours;
    //     minutes = minutes < 10 ? ('0' + minutes) : minutes;
    //     seconds = seconds < 10 && seconds >= 1 ? ('0' + seconds) : seconds;
    //
    //
    //     var year=new Date(parseInt(mss)).getYear();
    //     var month=new Date(parseInt(mss)).getMonth()+1;
    //     var date=new Date(parseInt(mss)).getDate();
    //     var hour=new Date(parseInt(mss)).getHours();
    //     var minute=new Date(parseInt(mss)).getMinutes();
    //     var second=new Date(parseInt(mss)).getSeconds();
    //     hour = hour < 10 ? ('0' + hour) : hour;
    //     minute = minute < 10 ? ('0' + minute) : minute;
    //     return  hour+":"+minute;
    // },
    GetQueryString:function(name)
    {
         var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
         var r = window.location.search.substr(1).match(reg);
         if(r!=null)return  unescape(r[2]); return null;
    },
    getUrlAddress:function(path){
    	var pathname = window.location.pathname;
    	// 获取系统根路径
    	var root = pathname.split("/")[1];
    	return window.location.protocol + "//" + window.location.host + "/" + root + "/" + (path ? path : "");
    },
    fmtDateTime:function(obj){
        var date =  new Date(obj);
        var y = 1900+date.getYear();
        var m = "0"+(date.getMonth()+1);
        var d = "0"+date.getDate();
        var h = date.getHours();
        var mi=date.getMinutes();
        var s = date.getSeconds();
        return y+"-"+m.substring(m.length-2,m.length)+"-"+d.substring(d.length-2,d.length)+" "+h+":"+mi+":"+s;
    },

};


var _clickButton = {
	successButton:function(label){
		$("#toast p").html(label);
		if ($("#toast").css('display') != 'none') return;
		$("#toast").fadeIn(100);
        setTimeout(function () {
        	$("#toast").fadeOut(100);
        }, 2000);
	},
	_toast:function(msg, duration, callback){
		weui.toast(msg, {
			duration : duration || 3000,
			className : "",
			callback : callback || function() {}
		});
	},
	formatDateTime:function(timeStamp) {   
	    var date = new Date();  
	    date.setTime(timeStamp * 1000);  
	    var y = date.getFullYear();      
	    var m = date.getMonth() + 1;      
	    m = m < 10 ? ('0' + m) : m;      
	    var d = date.getDate();      
	    d = d < 10 ? ('0' + d) : d;      
	    var h = date.getHours();    
	    h = h < 10 ? ('0' + h) : h;    
	    var minute = date.getMinutes();    
	    var second = date.getSeconds();    
	    minute = minute < 10 ? ('0' + minute) : minute;      
	    second = second < 10 ? ('0' + second) : second;     
	    return y + '-' + m + '-' + d+' '+h+':'+minute+':'+second;      
	},
	formatDate:function(timeStamp) {   
	    var date = new Date();  
	    date.setTime(timeStamp);  
	    var y = date.getFullYear();      
	    var m = date.getMonth() + 1;      
	    m = m < 10 ? ('0' + m) : m;      
	    var d = date.getDate();      
	    d = d < 10 ? ('0' + d) : d;      
	    var h = date.getHours();    
	    h = h < 10 ? ('0' + h) : h;    
	    var minute = date.getMinutes();    
	    var second = date.getSeconds();    
	    minute = minute < 10 ? ('0' + minute) : minute;      
	    second = second < 10 ? ('0' + second) : second;     
	    return y + '-' + m + '-' + d;      
	},
	 // 底部图标设置
    changeFooterImg:function(flag){
    	if(flag=="1"){
    		$("#Whome span img").attr("src", $("#Whome span img").data("url"));
    	}else if(flag=="2"){
    		
    	}else if(flag=="3"){
    		
    	}else{
    		$("#WmyInfo span img").attr("src",$("#WmyInfo span img").data("url"));
    	}
    }
}


var _util = {
    /**
	 * 解析链接地址中的参数信息，封装成obj对象返回，
	 * 
	 * @returns {*}
	 */
    parseUrl: function (url) {
        url = url || location.href;
        if (url.indexOf("?") != -1) {
            var arr = url.split("?")[1].split("&");
            var array = {};
            for (var i = 0; i < arr.length; i++) {
                array[arr[i].split("=")[0]] = arr[i].split("=")[1];
            }
            return array;
        } else {
            return null;
        }
    },
    /**
	 * 截取字符串长度
	 */
    colvalue: function (cv, count) {
        if (cv.length > count) {
            var pattern = RegExp("(<IMG\\s*[\\S]*\\s*/\\s*>)([\\S]*)");
            if (pattern.exec(cv)) {
                var str1 = RegExp.$1;
                var str2 = RegExp.$2;
                return str1 + str2.substring(0, count) + "...";
            } else {
                return cv.substring(0, count) + "...";
            }
        } else {
            return cv;
        }
    },
    /**
	 * 时间格式转化（毫秒转化日期）
	 */
    getDateTime:function(st){
    	
    },
    /**
	 * 转换成日期格式
	 * 
	 * @param st
	 * @returns {Date}
	 */
    getDate: function (st) {
        var a = st.split(" ");
        var b = a[0].split("-");
        var date;
        if (a.length > 1) {
            var c = a[1].split(":");
            date = new Date(b[0], b[1] - 1, b[2], c[0], c[1], c[2]);
        } else {
            date = new Date(b[0], b[1] - 1, b[2]);
        }
        return date;

    },
    /**
	 * 计算两个日期相关天数
	 * 
	 * @param sDate1
	 * @param sDate2
	 * @returns {Number|*}
	 * @constructor
	 */
    DateDiff: function (sDate1, sDate2) { // sDate1和sDate2是2006-12-18格式
    	if(sDate2==null || sDate2==""){
    		var myDate = new Date(); 
    		var y = 1900+myDate.getYear();
    		var m = myDate.getMonth()+1;
    		var d = myDate.getDate();
    		sDate2 = y+"-"+m+"-"+d;
    	}

        var iDays = parseInt(Math.abs(this.getDate(sDate1).getTime()
                - this.getDate(sDate2).getTime())
            / 1000 / 60 / 60 / 24) // 把相差的毫秒数转换为天数
        return iDays
    },
    /**
	 * 解析ehart格式 data一般为表格数据
	 */
    parseChartData: function (data) {
        var returnObj = {};
        if (data && data.length) {
            createOption(data[0]);// 获取数据的列头
            for (var i = 0; i < data.length; i++) {
                var dataObj = data[i];
                for (var k in returnObj) {
                    returnObj[k].push(dataObj[k] || 0);
                }
            }
        }
        /**
		 * 根据列头生成数组
		 * 
		 * @param dataObj
		 */
        function createOption(dataObj) {
            for (var k in dataObj) {
                returnObj[k] = [];
            }
        }

        return returnObj;
    },
    /**
	 * 从数组中取一个值返回新数组
	 * 
	 * @param Arr
	 * @param key
	 */
    getArray: function (Arr, key) {
        var returnA = [];
        if (Arr && Arr.length) {
            for (var i = 0; i < Arr.length; i++) {
                returnA.push(Arr[i][key]);
            }
        }
        return returnA;
    },
    /**
	 * 对象深度克隆
	 * 
	 * @param obj
	 * @returns
	 */
    cloneObj: function (obj) {
        var str, newobj = obj.constructor === Array ? [] : {};
        if (typeof obj !== 'object') {
            return;
        } else if (window.JSON) {
            str = JSON.stringify(obj), // 系列化对象
                newobj = JSON.parse(str); // 还原
        } else {
            for (var i in obj) {
                newobj[i] = typeof obj[i] === 'object' ? cloneObj(obj[i]) : obj[i];
            }
        }
        return newobj;
    }
}

CookieUtil = {
	get: function (k) {
		 if (document.cookie.length > 0) {
		    var cStart = document.cookie.indexOf(k + '=')
		    if (cStart !== -1) {
		      cStart = cStart + k.length + 1
		      var cEnd = document.cookie.indexOf(';', cStart)
		      if (cEnd === -1) cEnd = document.cookie.length
		      return decodeURIComponent(document.cookie.substring(cStart, cEnd))
		    }
		  } else {
		    return null
		  }
	},
	set: function (k, v) {
	  this.setCookieAndExpires(k, v, 30)
	},
	setCookieAndExpires: function (k, v, expires) {
		var Days = expires
		var exp = new Date()
		exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
		document.cookie = k + '=' + decodeURIComponent(v) + ';expires=' + exp.toGMTString()
	},
	remove: function (k) {
		var exp = new Date()
		exp.setTime(exp.getTime() - 1)
		var value = JqUtil.getCookie(k)
		if (value !== null) {
			  document.cookie = k + '=' + value + ';expires=' + exp.toGMTString()
		}
	}
}
